package com.zzptc.easyshop.servlet;

import com.zzptc.easyshop.dao.IDAO;
import com.zzptc.easyshop.dao.ProductDao;
import com.zzptc.easyshop.util.ShopCarUtil;
import com.zzptc.easyshop.vo.Product;
import com.zzptc.easyshop.vo.ShopCarGood;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ShopCarServlet")
public class ShopCarServlet extends HttpServlet {
    List<ShopCarGood> carlist;//设置全局变量
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //System.out.println("..........");
        //1、获取ID
        int id=0;
        if (request.getParameter("id")!=null){
            String sid=request.getParameter("id");
            id=Integer.parseInt(sid);
        }
        //2、根据ID查询该商品的详情
        IDAO dao=new ProductDao();
        Product product=null;
        try {
             product=((ProductDao)dao).getProductByid(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //3、将该商品添加到购物车
        //1、购物车是什么？ List 2、要保证始终是一台购物车
        if (carlist==null){
            carlist=new ArrayList<ShopCarGood>();
        }
        ShopCarGood shopCarGood=new ShopCarGood();
        shopCarGood.setId(product.getEp_id());
        shopCarGood.setName(product.getEp_name());
        shopCarGood.setPrice(product.getEp_price());
        shopCarGood.setNum(1);
        shopCarGood.setPicfile(product.getEp_file_name());

        //将商品添加到购物车(如果第一次添加：add；如果不是第一次添加，就只要将数量+1)
        ShopCarUtil.addGood(shopCarGood,carlist);
        //换做一个域  域对象
        HttpSession se=request.getSession();
        se.setAttribute("shop",carlist);
        //request.setAttribute("shop",carlist);
        //request.getRequestDispatcher("shopping.jsp").forward(request,response);
        response.sendRedirect("shopping.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
